using Godot;
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using TopDownGodot.Src.Globals.Multiplayer;

namespace TopDownGodot.Src.Game
{
    public partial class Main : Node
    {
        private readonly PackedScene _characterChoicesScene = GD.Load<PackedScene>("res://scene/character_choices.tscn");
        private readonly PackedScene _multiplayerScene = GD.Load<PackedScene>("res://scene/multiplayer_scene.tscn");

        /// <summary>
        /// 单实例应用 正式版上线开放
        /// </summary
        //[DllImport("user32.dll")]
        //private static extern bool SetForegroundWindow(IntPtr hWnd);
        //public override void _EnterTree()
        //{
        //    // 获取当前进程名
        //    string currentProcessName = Process.GetCurrentProcess().ProcessName;

        //    // 查找同名的其他进程（排除自己）
        //    Process[] existingProcesses = Process.GetProcessesByName(currentProcessName)
        //        .Where(p => p.Id != Process.GetCurrentProcess().Id)
        //        .ToArray();

        //    if (existingProcesses.Length > 0)
        //    {
        //        GD.Print("已有实例在运行，激活窗口并退出当前进程");

        //        // 尝试激活第一个找到的窗口
        //        IntPtr mainWindowHandle = existingProcesses[0].MainWindowHandle;
        //        if (mainWindowHandle != IntPtr.Zero)
        //        {
        //            SetForegroundWindow(mainWindowHandle);
        //        }

        //        // 退出当前进程
        //        GetTree().Quit();
        //        return;
        //    }

        //    GD.Print("这是第一个实例，继续运行");
        //}

        public void OnPlayerButtonPressed()
        {
            MultiplayerGlobal.IsMultiplayer = false;
            GetTree().ChangeSceneToPacked(_characterChoicesScene);
        }

        public void OnMultiplayerGamePressed()
        {
            MultiplayerGlobal.IsMultiplayer = true;
            GetTree().ChangeSceneToPacked(_multiplayerScene);
        }

        public void OnGameQuitPressed()
        {
            GetTree().Quit(0);
        }
    }
}